<?php
namespace app\common\model;
use app\common\exception\BaseException;
use think\Request;
use think\Session;
use think\Cache;
use think\Db;

/**
 * 微信小程序模型
 */
class Wxapp extends BaseModel
{
    protected $name = 'wxapp';
    protected $append = ['new_tpl'];
	
	/**
     * 版本状态
     */
    public function getNewTplAttr($value, $data)
    {
    	if($data['is_empower'] == 1){
	    	if($data['template']==0){
	        	return ['value'=>1,'text'=>'发布'];
	        }
	        $new = Template::getNew($data['app_type']);
	        if($new['template_id']>$data['template']){
	        	return ['value'=>1,'text'=>'升级'];
	        }
	        if($new['template_id']==$data['template']){
	        	$wxappTpl = WxappTpl::getNew($data['wxapp_id']);
	        	if($wxappTpl['status']==0){
	        		$desc = getAuditStatus($wxappTpl['auditid'],$data['wxapp_id']);
	        		if(isset($desc['status'])){
		        		if($desc['status']==0){
		        			return ['value'=>0,'text'=>'待发布'];
		        		}
		        		if($desc['status']==1){
		        			return ['value'=>1,'text'=>'被拒绝'];
		        		}
		        		if($desc['status']==2){
		        			return ['value'=>0,'text'=>'审核中'];
		        		}
		        		if($desc['status']==3){
		        			return ['value'=>1,'text'=>'被撤回'];
		        		}
		        		if($desc['status']==4){
		        			return ['value'=>0,'text'=>'审核延后'];
		        		}
	        		}
	        	}
	        }
        }
		return false;
    }

    /**
     * 微信头像
     */
    public function getHeadImgAttr($value)
    {
        empty($value) && $value = web_url() . 'assets/images/wxapp.png';
        return $value;
    }
	
	/**
     * 账号来源
     */
    public function getSourceAttr($value)
    {
        $status = [10 => '自注', 20 => '平台'];
        return ['text' => $status[$value], 'value' => $value];
    }
	
	/**
     * 是否授权
     */
    public function getIsEmpowerAttr($value)
    {
        $status = ['否','是'];
        return ['text' => $status[$value], 'value' => $value];
    }
	
	/**
     * 是否试用
     */
    public function getIsTestAttr($value)
    {
        $status = ['否','是'];
        return ['text' => $status[$value], 'value' => $value];
    }
	
	/**
     * 支付账号类型
     */
    public function getIsSubAttr($value)
    {
        $status = ['主账户','子账户'];
        return ['text' => $status[$value], 'value' => $value];
    }
	
	/**
     * 自定义底部授权信息
     */
    public function getIsCopyrightAttr($value)
    {
        $status = ['关闭','开启'];
        return ['text' => $status[$value], 'value' => $value];
    }
	
	/**
     * 小程序类型
     */
    public function getAppTypeAttr($value)
    {
		$app_type = WebEdition::getAppType($value);
        return ['text' => $app_type['name'], 'value' => $app_type['app_type']];
    }
	
	/**
     * 门店类型
     */
    public function getShopModeAttr($value)
    {
		$status = [10 => '单', 20 => '多'];
        return ['text' => $status[$value], 'value' => $value];
    }
	
	/**
     * 设置小程序模板信息
     */
    public function getTemplateAttr($value)
    {
		if($value==0){
			return ['template_id' => $value];
		}
		return Template::detail($value);
         
    }
	
	/**
     * 到期时间
     */
    public function getExpireTimeAttr($value)
    {
		$day = round(($value - time()) / 86400);
        return ['text' => date("Y-m-d", $value), 'value' => $value, 'day' => $day];
    }
	
	/**
     * 获取列表 
     */
    public function getList($store_user_id=0,$expire_time='',$is_empower='',$agent_id='')
    {
		// 筛选条件
        $filter = [];
        $store_user_id > 0 && $filter['store_user_id'] = $store_user_id;
		!empty($is_empower) && $filter['is_empower'] = $is_empower;
		!empty($agent_id) && $filter['agent_id'] = $agent_id;
		if(!empty($expire_time)){
			if($expire_time == 0){
				//未到期
				$filter['expire_time'] = ['>',time()];
			}elseif($expire_time == 1){
				//即将到期
				$filter['expire_time'] = ['<',time()+30*86400];
			}else{
				//已到期
				$filter['expire_time'] = ['<',time()];
			}
		}
        // 执行查询
        $list = $this->useGlobalScope(false)
            ->where($filter)
            ->order('wxapp_id','desc')
            ->paginate(15, false, [
                'query' => Request::instance()->request()
            ]);
        return $list;
    }
	
    /**
     * 获取小程序信息
     */
    public static function detail()
    {
        return self::get([]);
    }

	/**
     * 获取小程序信息 - 回调接口
     */
    public static function getWxapp($where)
    {
        return self::useGlobalScope(false)->where($where)->find();
    }

    /**
     * 从缓存中获取小程序信息
     */
    public static function getWxappCache($wxapp_id = null)
    {
        if (is_null($wxapp_id)) {
            $self = new static();
            $wxapp_id = $self::$wxapp_id;
        }
        if (!$data = Cache::get('wxapp_' . $wxapp_id)) {
            $data = self::get($wxapp_id);
            if (empty($data)) throw new BaseException(['msg' => '未找到当前小程序信息']);
            Cache::set('wxapp_' . $wxapp_id, $data);
        }
        return $data;
    }
	
	/**
     * 管理员/代理执行应用登录
     */
    public function appLogin()
    {
		if($store = StoreUser::detail($this->store_user_id)){
			// 保存登录状态
			Session::set('hema_store', [
				'user' => [
					'store_user_id' => $store['store_user_id'],
					'user_name' => $store['user_name'],
					'agent_id' => $store['agent_id'],
                    'avatarUrl' => $store['avatarUrl']
				],
				'wxapp' => $this->toArray(),
				'is_login' => true,
				'is_admin' => true,
			]);
			return true;
		}
		return false;
    }

    /**
     * 创建小程序
     */
    /**
     * 创建小程序
     * @param [type] $data     数据
     * @param string $dataType 数据类型 app=用户新增,apply=平台入驻
     */
    public function add($data,$dataType='app')
    {
    	$pay = 0;//支付费用
    	if($dataType=='app'){
			if(!isMobile($data['phone'])){
				$this->error = '手机号码错误';
	            return false;	
			}
			$edition = WebEdition::detail($data['web_edition_id']);//获取版本详情
			$store = StoreUser::detail($data['store_user_id']);//获取商户详情
			$agent_price = 0;//代理费用
			//判断是否试用
			if($data['year']>0){
				//计算费用
				if($data['shop_mode']==10){
					//单商户
					if($store['wallet'] < $edition['buy_single'][$data['year']]){
						$this->error = '账户余额不足，请充值';
						return false;
					}
					$pay = $edition['buy_single'][$data['year']];
					$agent_price = $edition['single_price']*$data['year'];
				}
				if($data['shop_mode']==20){
					//多商户
					if($store['wallet'] < $edition['buy_many'][$data['year']-1]){
						$this->error = '账户余额不足，请充值';
						return false;
					}
					$pay = $edition['buy_many'][$data['year']-1];
					$agent_price = $edition['many_price']*$data['year'];
				}
				$expire_time = strtotime('+'.$data['year'].'year');//计算到期时间
				$data['is_test'] = 0;//不是试用
			}else{
				$expire_time = time()+$edition['trial_day']*3600*24;//计算到期时间
			}
			$data['expire_time'] = $expire_time;
			$data['app_type'] = $edition['app_type'];
		}
		// 开启事务
        Db::startTrans();
        try {
			//扣费
			if($dataType=='app' AND $pay>0){
				$order_list = [];
				array_push($order_list,[
					'order_no' => orderNo(),
					'order_type' => 20,
					'pay_price' => $pay,
					'pay_status' => 20,
					'pay_time' => time(),
					'purpose' => '购买小程序',
					'affair_id' => $data['store_user_id'],
					'agent_id' => $data['agent_id']
				]);
				//用户扣费
				$wallet = $store['wallet']-$pay;//计算扣除后的余额
				$store->wallet = ['dec',$pay];
				$store->save();
				//代理分账
				if($data['agent_id']>0){
					//管理总账户扣费
					$admin = StoreUser::getStore(['is_agent' => 2]);
					$admin->wallet = ['dec',$pay-$agent_price];
					$admin->save();
					//代理分红
					$agent = StoreUser::getStore(['agent_id' => $data['agent_id']]);
					$agent->wallet = ['inc',$pay-$agent_price];
					$agent->save();
					array_push($order_list,[
						'order_no' => orderNo(),
						'order_type' => 30,
						'pay_price' => $pay-$agent_price,
						'pay_status' => 20,
						'pay_time' => time(),
						'purpose' => '购买分红',
						'affair_id' => $data['agent_id'],
						'agent_id' => $data['agent_id']
					]);						
				}
				//添加流水记录
				$order = new WebOrder;
				$order->saveAll($order_list);
			}
			// 添加小程序记录
			$this->allowField(true)->save($data);
			// 新增小程序diy配置
			$Page = new WxappPage;
			$Page->insertDefault($this->wxapp_id,$data);
			// 新增默认门店
			$Shop = new Shop;
			$Shop->insertDefault($this->wxapp_id,$data);
			// 新增用户等级
			$UserGrade = new UserGrade;
			$UserGrade->insertDefault($this->wxapp_id);
			// 新增小程序帮助
			$WxappHelp = new WxappHelp;
			$WxappHelp->insertDefault($this->wxapp_id);

			Db::commit();
			if($dataType=='app'){
				if($pay>0){
					//账户资金变动提醒
					sand_account_change_msg('购买小程序管理系统',$pay,$wallet,$data['store_user_id']);
				}else{
					//试用申请成功通知
					sand_testing_msg('小程序管理系统',$expire_time,$data['store_user_id']);
				}
			}
            return $this->wxapp_id;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
    }
	/**
     * 批量删除小程序数据
     */
    public function deleteBatch($wxapp_id)
    {
		$where['wxapp_id'] = $wxapp_id;
		// 开启事务
        Db::startTrans();
        try {
        	//拼团商品
        	GoodsGroup::useGlobalScope(false)->where($where)->delete();
        	//申请记录
			StoreApply::useGlobalScope(false)->where($where)->delete();
			//砍价商品
			GoodsBargain::useGlobalScope(false)->where($where)->delete();
			//秒杀商品
			GoodsSeckill::useGlobalScope(false)->where($where)->delete();
			//云叫号
			Calling::useGlobalScope(false)->where($where)->delete();
			//免费吃
			FreeGoods::useGlobalScope(false)->where($where)->delete();
			//图文消息
			Article::useGlobalScope(false)->where($where)->delete();
			//图文分类
			ArticleCategory::useGlobalScope(false)->where($where)->delete();
			//直播间
			LiveRoom::useGlobalScope(false)->where($where)->delete();
			//预约
			Pact::useGlobalScope(false)->where($where)->delete();
			//分销商进出帐
			Dealer::useGlobalScope(false)->where($where)->delete();
			//口味选项
			Flavor::useGlobalScope(false)->where($where)->delete();
			//附近小程序类目
			NearbyCategory::useGlobalScope(false)->where($where)->delete();
			//附近小程序
			Nearby::useGlobalScope(false)->where($where)->delete();
			//小程序体验用户
			TestUser::useGlobalScope(false)->where($where)->delete();
			//小程序服务类目
			CategoryServe::useGlobalScope(false)->where($where)->delete();
			//商家发布的小程序模板
			WxappTpl::useGlobalScope(false)->where($where)->delete();
			//小程序名称设置记录
			WxappName::useGlobalScope(false)->where($where)->delete();
			//评价记录
			Comment::useGlobalScope(false)->where($where)->delete();
			//充值套餐
			RechargePlan::useGlobalScope(false)->where($where)->delete();
			//充值记录
			Recharge::useGlobalScope(false)->where($where)->delete();
			//优惠活动
			Activity::useGlobalScope(false)->where($where)->delete();
			//云打印机
			Printer::useGlobalScope(false)->where($where)->delete();
			//打印任务列表
			PrinterLog::useGlobalScope(false)->where($where)->delete();
			//餐桌
			Table::useGlobalScope(false)->where($where)->delete();
			//店员
			ShopClerk::useGlobalScope(false)->where($where)->delete();
			//商品
			Category::useGlobalScope(false)->where($where)->delete();
			Goods::useGlobalScope(false)->where($where)->delete();
			GoodsImage::useGlobalScope(false)->where($where)->delete();
			GoodsSpec::useGlobalScope(false)->where($where)->delete();
			GoodsSpecRel::useGlobalScope(false)->where($where)->delete();
			Spec::useGlobalScope(false)->where($where)->delete();
			SpecValue::useGlobalScope(false)->where($where)->delete();
			//订单
			Order::useGlobalScope(false)->where($where)->delete();
			OrderAddress::useGlobalScope(false)->where($where)->delete();
			OrderGoods::useGlobalScope(false)->where($where)->delete();
			//图片
			UploadFile::useGlobalScope(false)->where($where)->delete();
			UploadGroup::useGlobalScope(false)->where($where)->delete();
			//商家设置
			Setting::useGlobalScope(false)->where($where)->delete();

			//商家帮助
			WxappHelp::useGlobalScope(false)->where($where)->delete();
			//小程序页面
			WxappPage::useGlobalScope(false)->where($where)->delete();
			//用户
			User::useGlobalScope(false)->where($where)->delete();
			UserAddress::useGlobalScope(false)->where($where)->delete();
			UserGrade::useGlobalScope(false)->where($where)->delete();
			//门店
			Shop::useGlobalScope(false)->where($where)->delete();
			//小程序
			Wxapp::useGlobalScope(false)->where($where)->delete();
			Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
	}

	/**
     * 上传小程序模板
     */
    public function publish()
    {
    	//获取最新版本
		$new_tpl = Template::getNew($this['app_type']['value']);
		//执行上传代码模板
		if($result = publish($this, $new_tpl)){
			$this->error = wx_err_msg($result);
            return false;
		}	
		$result = audit($this['wxapp_id']);	
		if($result['errcode']!= 0){
			$this->error = wx_err_msg($result['errcode']);
            return false;
		}
		$auditid = $result['auditid'];//获取审核编号
		// 开启事务
        Db::startTrans();
        try {
        	Cache::rm('wxapp_' . $this['wxapp_id']);
			//添加商户发布的模板记录
			$tpl = new WxappTpl;
	        $tpl->template = $new_tpl['template_id'];
			$tpl->auditid = $auditid;
			$tpl->wxapp_id = $this['wxapp_id'];
			$tpl->save();
			$this->template = $new_tpl['template_id'];//指定当前已上传新版本
			$this->save();
			Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;

	}

	/**
     * 更新小程序设置
     */
    public function edit($data)
    {
        // 删除wxapp缓存
        self::deleteCache();
        if(isset($data['api_domain']) AND $this->api_domain != $data['api_domain']){
            setServedomain($data['api_domain']);
        }
        if(isset($data['signature']) AND $this->signature != $data['signature']){
            setSignature($data['signature']);
        }
        if(isset($data['is_empower'])){
			Session::set('hema_store.wxapp.is_empower.value',$data['is_empower']);
        }
        return $this->allowField(true)->save($data) !== false;
    }
	
	/**
     * 根据条件统计数量
     */
    public static function getCount($agent_id=0)
    {
		$self = new static;
        $count = array();
		//全部统计
		$count['all']['all'] = self::useGlobalScope(false)->count();//全部数量
		$count['all']['agent'] = self::useGlobalScope(false)->where(['agent_id' => ['>',0]])->count();//全部代理数量
		$count['all']['normal'] = self::useGlobalScope(false)->where(['is_empower' => 1])->count();//全部已授权
		$count['all']['warn'] = self::useGlobalScope(false)->where(['expire_time' => ['<',time()+30*86400]])->count();//全部将到期
		$count['all']['ends'] = self::useGlobalScope(false)->where(['expire_time' => ['<',time()]])->count();//全部已到期
		$count['agent']['all'] = self::useGlobalScope(false)->where(['agent_id' => $agent_id])->count();//所属代理数量
		$count['agent']['normal'] = self::useGlobalScope(false)->where(['agent_id' => $agent_id,'is_empower' => 1])->count();//所属代理已授权
		$count['agent']['warn'] = self::useGlobalScope(false)->where(['agent_id' => $agent_id,'expire_time' => ['<',time()+30*86400]])->count();//所属代理将到期
		$count['agent']['ends'] = self::useGlobalScope(false)->where(['agent_id' => $agent_id,'expire_time' => ['<',time()]])->count();//所属代理已到期
		//今天统计
		$star = strtotime(date('Y-m-d 00:00:00',time()));
		$count['today']['all'] = self::useGlobalScope(false)->where(['create_time' => ['>',$star]])->count();//全部数量
		$count['today']['agent'] = self::useGlobalScope(false)->where(['agent_id' => $agent_id,'create_time' => ['>',$star]])->count();//所属代理数量
		//昨天统计
		$star = strtotime("-1 day");
		$end = strtotime(date('Y-m-d 00:00:00',time()));
		$count['today2']['all'] = self::useGlobalScope(false)->where('create_time','>',$star)->where('create_time','<',$end)->count();//全部数量
		$count['today2']['agent'] = self::useGlobalScope(false)->where('create_time','>',$star)->where('create_time','<',$end)->where(['agent_id' => $agent_id])->count();//所属代理数量
		//前天统计
		$star = strtotime("-2 day");
		$end = strtotime("-1 day");
		$count['today3']['all'] = self::useGlobalScope(false)->where('create_time','>',$star)->where('create_time','<',$end)->count();//全部数量
		$count['today3']['agent'] = self::useGlobalScope(false)->where('create_time','>',$star)->where('create_time','<',$end)->where(['agent_id' => $agent_id])->count();//所属代理数量
		//-4天统计
		$star = strtotime("-3 day");
		$end = strtotime("-2 day");
		$count['today4']['all'] = self::useGlobalScope(false)->where('create_time','>',$star)->where('create_time','<',$end)->count();//全部数量
		$count['today4']['agent'] = self::useGlobalScope(false)->where('create_time','>',$star)->where('create_time','<',$end)->where(['agent_id' => $agent_id])->count();//所属代理数量
		//-5天统计
		$star = strtotime("-4 day");
		$end = strtotime("-3 day");
		$count['today5']['all'] = self::useGlobalScope(false)->where('create_time','>',$star)->where('create_time','<',$end)->count();//全部数量
		$count['today5']['agent'] = self::useGlobalScope(false)->where('create_time','>',$star)->where('create_time','<',$end)->where(['agent_id' => $agent_id])->count();//所属代理数量
		//-6天统计
		$star = strtotime("-5 day");
		$end = strtotime("-4 day");
		$count['today6']['all'] = self::useGlobalScope(false)->where('create_time','>',$star)->where('create_time','<',$end)->count();//全部数量
		$count['today6']['agent'] = self::useGlobalScope(false)->where('create_time','>',$star)->where('create_time','<',$end)->where(['agent_id' => $agent_id])->count();//所属代理数量
		//-7天统计
		$star = strtotime("-6 day");
		$end = strtotime("-5 day");
		$count['today7']['all'] = self::useGlobalScope(false)->where('create_time','>',$star)->where('create_time','<',$end)->count();//全部数量
		$count['today7']['agent'] = self::useGlobalScope(false)->where('create_time','>',$star)->where('create_time','<',$end)->where(['agent_id' => $agent_id])->count();//所属代理数量
		//本月统计 
		$end = mktime(0,0,0,date('m'),1,date('y')); 
		$count['month']['all'] = self::useGlobalScope(false)->where('create_time','>',$end)->count();//全部数量
		$count['month']['agent'] = self::useGlobalScope(false)->where('create_time','>',$end)->where(['agent_id' => $agent_id])->count();//所属代理数量
		//上月统计  
		$star = mktime(0,0,0,date('m')-1,1,date('y'));
		$count['month2']['all'] = self::useGlobalScope(false)->where('create_time','>',$star)->where('create_time','<',$end)->count();//全部数量
		$count['month2']['agent'] = self::useGlobalScope(false)->where('create_time','>',$star)->where('create_time','<',$end)->where(['agent_id' => $agent_id])->count();//所属代理数量
		return $count;
    }

    /**
     * 删除wxapp缓存
     */
    public static function deleteCache()
    {
        return Cache::rm('wxapp_' . self::$wxapp_id);
    }
}
